package com.device.service;

import com.alibaba.fastjson.JSONObject;
import com.device.dataobject.vo.ResultVO;
import com.device.entity.AliyunOssResult;
import com.device.entity.Device;
import com.device.dataobject.device.DeviceDetail;
import com.device.entity.UserDevice;
import com.device.enums.CacheEnum;
import com.device.enums.FileType;
import com.device.repository.DeviceRepository;
import com.device.repository.UserDeviceRepository;
import com.device.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeviceService {

    private final DeviceRepository deviceRepository;
    private final UserDeviceRepository userDeviceRepository;
    private final FileUploadService fileUploadService;
    private final RedisTemplate<String, Object> redisTemplate;
    @Autowired
    public DeviceService(DeviceRepository deviceRepository, UserDeviceRepository userDeviceRepository, FileUploadService fileUploadService, RedisTemplate<String, Object> redisTemplate) {
        this.deviceRepository = deviceRepository;
        this.userDeviceRepository = userDeviceRepository;
        this.fileUploadService = fileUploadService;
        this.redisTemplate = redisTemplate;
    }


    public List<Device> getAllDevices(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Device> devices = deviceRepository.findAll(pageable);
        return devices.getContent();
    }

    public Device getDeviceById(Integer id) {
        return deviceRepository.findById(id).orElse(null);
    }

    public List<Device> searchDevices(Integer page, Integer size, String deviceName) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Device> devices = deviceRepository.findByDeviceNameContaining(deviceName, pageable);
        return devices.getContent();
    }

    public Pageable getPageable(JSONObject jsonObject){
        Integer page =  jsonObject.getInteger("page");
        Integer size = jsonObject.getInteger("size");
        return PageRequest.of(page - 1, size);
    }


    public List<DeviceDetail> getDeviceByAreaAndName(JSONObject jsonObject) {

        Pageable pageable = getPageable(jsonObject);
        List<UserDevice> userDevices = userDeviceRepository.findByAreaAndDeviceNameAndStatus(jsonObject.getString("area"), jsonObject.getString("deviceName"), true,pageable).getContent();

        Map<String, List<UserDevice>> deviceMap = new HashMap<>();

        // 归类设备
        for (UserDevice userDevice : userDevices) {
            String key = userDevice.getArea() + "_" + userDevice.getRentPrice();

            if (deviceMap.containsKey(key)) {
                deviceMap.get(key).add(userDevice);
            } else {
                List<UserDevice> newList = new ArrayList<>();
                newList.add(userDevice);
                deviceMap.put(key, newList);
            }
        }


        List<DeviceDetail> deviceDetails = new ArrayList<>();

        // 构造DeviceDetail对象
        for (List<UserDevice> deviceList : deviceMap.values()) {
            DeviceDetail deviceDetail = new DeviceDetail();
            deviceDetail.setArea(deviceList.get(0).getArea());
            deviceDetail.setRentPrice(deviceList.get(0).getRentPrice());
            deviceDetail.setUserDevices(deviceList);

            deviceDetails.add(deviceDetail);
        }

        return deviceDetails;
    }

    public List<String> getDeviceNameList(){


        // 尝试从Redis缓存中获取设备名称列表
        List<String> cachedDeviceNames = (List<String>) redisTemplate.opsForValue().get(CacheEnum.DEVICE_NAMES.name());

        if (cachedDeviceNames != null) {
            // 缓存命中，直接返回结果
            return cachedDeviceNames;
        } else {
            // 从数据库查询设备列表
            List<Device> devices = deviceRepository.findAll();
            List<String> deviceNames = devices.stream().map(Device::getDeviceName).collect(Collectors.toList());

            // 将结果存入Redis缓存中
            redisTemplate.opsForValue().set(CacheEnum.DEVICE_NAMES.name(), deviceNames);

            return deviceNames;
        }

    }

    public ResultVO uploadImage(MultipartFile file) {

        // Upload image to OSS
        AliyunOssResult result = fileUploadService.uploadFile(file, FileType.DEVICE);

        // Update avatar URL and save to the database

        return ResultVOUtil.returnSuccess(result.getUrl());
    }




}


